<template>
  <view class="container">
    <u-form :model="formData" ref="data" :rules="rules1" label-width="120" class="t_form">
      <u-form-item label="手机号" prop="phone" :border-bottom="false">
        <u-input v-model="formData.phone" :border="true" placeholder="请输入手机号" />
      </u-form-item>
      <u-form-item label="验证码" prop="code" :border-bottom="false">
        <u-input v-model="formData.code" :border="true" placeholder="请输入验证码" />
        <u-button slot="right" @click="getCode" style="margin-left: 20rpx;">{{codeTips}}</u-button>
      </u-form-item>
    </u-form>
    <view @click="submit1" class="button">提交</view>
    <!-- 验证码 -->
    <u-verification-code seconds="60" ref="ucode" @change="codeChange"></u-verification-code>
  </view>
</template>

<script setup>
  import {
    reactive,
    ref
  } from 'vue'
  import {
    onReady
  } from '@dcloudio/uni-app';
  import ui from '@/utils/index.js'
  const data = ref(null)
  const ucode = ref(null)
  const codeTips = ref('获取验证码')
  const formData = reactive({
    phone: '',
    code: ''
  })
  const rules1 = reactive({
    phone: [{
        required: true,
        message: '请输入手机号',
        trigger: ['change', 'blur'],
      },
      {
        // 自定义验证函数，见上说明
        validator: (rule, value, callback) => {
          return /^1[3-9]\d{9}$/.test(value)
        },
        message: '手机号码不正确',
        // 触发器可以同时用blur和change
        trigger: ['change', 'blur'],
      }
    ],
    code: [{
      required: true,
      message: '请输入验证码',
      trigger: ['change', 'blur'],
    }]
  })
  onReady(() => {
    data.value.setRules(rules1);
  })
  // 提交表单
  const submit1 = () => {
    data.value.validate().then(res => {
      console.log('表单数据信息：', res);
    }).catch(err => {
      console.log('表单错误信息：', err);
    })
  }
  // 获取验证码
  const getCode = () => {
    if (formData.phone.length === 0) {
      ui.toast('请输入手机号')
    } else if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
      ui.toast('手机号码不正确')
    } else {
      if (ucode.value.canGetCode) {
        ui.loading('正在获取验证码')
        // 获取验证码接口

        setTimeout(() => {
          // 通知验证码组件内部开始倒计时
          ucode.value.start();
          uni.hideLoading()
        }, 1000)

      } else {
        ui.toast('倒计时结束后再发送')
      }
    }
  }
  // 验证码回调
  const codeChange = (text) => {
    codeTips.value = text;
  }
</script>

<style lang="scss">
  .container {
    padding: 20rpx 30rpx;
    background-color: #fff;
  }
  .t_form {
    box-sizing: border-box;
    // background-color: #fff;
  }

  .button {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 100rpx;
    background-color: #7F7F7F;
    color: #fff;
    font-size: 30rpx;
    line-height: 100rpx;
    text-align: center;
  }
</style>